const express = require('express');
const router = express.Router();
const { sequelize } = require('../../config/database');

/**
 * 奖品兑换路由
 * POST /api/prizes/exchangePrize
 * 请求体: { studentId: number, prizeId: number }
 */
router.post('/exchangePrize', async (req, res) => {
  // 验证请求体
  const { studentId, prizeId } = req.body;
  
  if (!studentId || !prizeId) {
    return res.status(400).json({
      success: false,
      message: '缺少必要参数: studentId 或 prizeId'
    });
  }

  try {
    // 执行兑换逻辑
    const result = await exchangePrize(studentId, prizeId);
    
    if (result.success) {
      res.json({
        success: true,
        message: result.message,
        data: {
          studentId,
          prizeId,
          pointsUsed: result.pointsUsed,
          redeemCode: result.redeemCode // 返回兑换码
        }
      });
    } else {
      res.status(400).json({
        success: false,
        message: result.message
      });
    }
  } catch (error) {
    console.error('奖品兑换错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
});

/**
 * 奖品兑换核心逻辑（使用Sequelize事务）
 * @param {number} studentId - 学生ID
 * @param {number} prizeId - 奖品ID
 * @returns {Promise<{success: boolean, message: string, pointsUsed?: number, redeemCode?: string}>}
 */
async function exchangePrize(studentId, prizeId) {
  // 开启Sequelize事务
  const transaction = await sequelize.transaction();

  try {
    // 1. 检查学生积分是否足够
    const student = await sequelize.models.student.findOne({
      where: { id: studentId },
      lock: transaction.LOCK.UPDATE,
      transaction
    });
    
    if (!student) {
      throw new Error('学生不存在');
    }
    
    // 2. 检查奖品库存是否足够
    const prize = await sequelize.models.prize.findOne({
      where: { id: prizeId },
      lock: transaction.LOCK.UPDATE,
      transaction
    });
    
    if (!prize) {
      throw new Error('奖品不存在');
    }
    
    if (student.points < prize.points) {
      throw new Error('积分不足');
    }
    
    if (prize.stock <= 0) {
      throw new Error('奖品库存不足');
    }
    
    // 3. 扣除学生积分
    await student.decrement('points', {
      by: prize.points,
      transaction
    });
    
    // 4. 减少奖品库存
    await prize.decrement('stock', {
      by: 1,
      transaction
    });
    
    // 5. 生成兑换码
    const redeemCode = generateRedeemCode();
    
    // 6. 创建兑换记录（根据表结构调整）
    await sequelize.models.ExchangeRecord.create({
      student_id: studentId,
      prize_id: prizeId,
      points_used: prize.points,
      status: 'completed',
      redeem_code: redeemCode // 虽然表中没有这个字段，但保留以便返回给前端
      // exchange_time 会自动设置为当前时间
    }, { transaction });
    
    // 提交事务
    await transaction.commit();
    
    return { 
      success: true, 
      message: '兑换成功',
      pointsUsed: prize.points,
      redeemCode: redeemCode
    };
  } catch (error) {
    // 回滚事务
    if (transaction) await transaction.rollback();
    return { 
      success: false, 
      message: error.message 
    };
  }
}

// 生成随机兑换码
function generateRedeemCode() {
  const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // 避免容易混淆的字符
  const segments = [4, 4, 4]; // 三段，每段4个字符
  
  return segments.map(seg => {
    let result = '';
    for (let i = 0; i < seg; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
  }).join('-');
}

module.exports = router;